<?php

namespace App\Http\Middleware;

use Closure;
use App\Model\Log;

class AdminLog
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        $method = $request->method();
        if ($method != 'GET' && $method != 'OPTIONS') {
            $route = $request->route();
            $admin = $request->_admin;
            $input = $request->all();

            $log = new Log();
            $log->admin_id = $admin->id;
            $log->admin_name = $admin->name;
            $log->path = $request->path();
            $log->method = $method;
            $log->ip = $request->ip();
            $log->describe = $route->getName();
            if (!empty($input)) {
                $log->input = json_encode($input, JSON_UNESCAPED_UNICODE);
            }

            $log->created_date = date('Y-m-d H:i:s');
            $log->save();
        }
        return $response;
    }
}
